import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login')
  },
  {
    path: '/home',
    name: 'Home',
    redirect: '/welcome',
    component: () => import('../views/Home'),
    children: [
      { path: '/welcome', name: 'Welcome', component: () => import('../views/Welcome') },
      { path: '/users', name: 'Users', component: () => import('../views/Users') },
      { path: '/rights', name: 'Rights', component: () => import('../views/Rights') },
      { path: '/roles', name: 'Roles', component: () => import('../views/Roles') },
      { path: '/categories', name: 'Cate', component: () => import('../views/Goods/Cate') },
      { path: '/params', name: 'Params', component: () => import('../views/Goods/Params') },
      { path: '/goods', name: 'Goods', component: () => import('../views/Goods/List') },
      { path: '/goods/add', name: 'AddGoods', component: () => import('../views/Goods/Add') },
      { path: '/orders', name: 'Orders', component: () => import('../views/Orders') },
      { path: '/reports', name: 'Reports', component: () => import('../views/Reports') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 为路由对象添加beforeEach 导航守卫
router.beforeEach((to, from, next) => {
  // 如果用户访问登录页，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage中获取保存的token值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token，强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})

export default router
